<!--
 * @Author: wankong
 * @Desc: 编辑新文章页面
 * @Date: 2021-10-07 16:19:38
 * @LastEditTime: 2021-12-23 14:58:29
-->
<template>
  <el-main class="editor">
    <el-form :model="article" :rules="rules" ref="formRef" label-width="80px">
      <el-row :gutter="20">
        <!-- 左边 标题，内容 -->
        <el-col :span="18">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="article.title"
              placeholder="请输入标题"
            ></el-input>
          </el-form-item>
          <Editor
            :value="article.content"
            placeholder="写点什么吧"
            :plugins="plugins"
            :locale="i18"
            @change="handleChange"
          />
        </el-col>
        <!-- 标签、分类栏 右边 -->
        <el-col :span="6">
          <el-card>
            <template slot="header"> 配置项 </template>
            <!-- 分类选择 -->
            <el-form-item label="分类:" prop="sortid">
              <el-select v-model="article.sortid" placeholder="分类">
                <el-option label="请选择" :disabled="true" value="0">
                </el-option>
                <el-option
                  v-for="cate in cateList"
                  :key="cate.id"
                  :label="cate.catename"
                  :value="cate.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="主题:" prop="theme">
              <el-input
                v-model="article.theme"
                placeholder="请输入主题名"
              ></el-input>
            </el-form-item>
            <el-form-item label="封面图片:">
              <el-input
                v-model="article.image"
                placeholder="图片的URL地址"
              ></el-input>
            </el-form-item>
            <el-form-item label="浏览量:">
              <el-input
                type="number"
                v-model="article.views"
                placeholder="浏览量"
              ></el-input>
            </el-form-item>
            <el-form-item label="时间:" prop="ctime">
              <el-date-picker
                v-model="article.ctime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                default-time="12:00:00"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="置顶:">
              <el-checkbox v-model="article.istop">置顶</el-checkbox>
            </el-form-item>

            <!-- 标签选择 -->
            <div class="tags">
              <h4>选择标签</h4>
              <div class="chosed">
                <el-tag
                  :key="tag.id"
                  v-for="(tag, index) in chosedTaglist"
                  closable
                  :type="getTagType(index)"
                  :disable-transitions="false"
                  @close="tagRemove(index)"
                >
                  {{ tag.tagname }}
                </el-tag>
              </div>
              <el-divider></el-divider>
              <div class="tagList">
                <el-tag
                  :key="tag.id"
                  v-for="(tag, index) in tagList"
                  :type="getTagType(index)"
                  @click="addTagToList(index)"
                >
                  {{ tag.tagname }}
                </el-tag>
                <!-- 新增标签 -->
                <el-input
                  class="input-new-tag"
                  v-if="showTagInput"
                  v-model="inputTag"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm"
                  @blur="handleInputConfirm"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput"
                >
                  + 新增</el-button
                >
              </div>
            </div>
            <el-divider></el-divider>
            <el-button type="primary" @click="saveCache"> 保存草稿</el-button>
            <el-button type="success" @click="saveEditor"> 发布文章</el-button>
          </el-card>
        </el-col>
      </el-row>
    </el-form>
  </el-main>
</template>

<script>
import "bytemd/dist/index.min.css";
import { Editor } from "@bytemd/vue";
import gfm from "@bytemd/plugin-gfm";
import breaks from "@bytemd/plugin-breaks";

import customHrefTarget from "../../common/customHrefTarget";
import customToolBar from "../../common/bytemd/plugin-theme/customToolBar";
import highlightSsr from "@bytemd/plugin-highlight-ssr";
import gemoji from "@bytemd/plugin-gemoji";
import frontmatter from "@bytemd/plugin-frontmatter";

const i18 = require("../../common/byteMd_zh_Hans.json");
const plugins = [
  breaks(),
  frontmatter(),
  gfm({
    locale: i18,
  }),
  customHrefTarget(),
  highlightSsr(),
  gemoji(),
  customToolBar(),
];
export default {
  components: {
    Editor,
  },
  watch: {},
  data() {
    return {
      article: {
        id: null,
        title: "我是标题",
        content: "我是内容啊！！！",
        sortid: "",
        theme: "default",
        image: "",
        ctime: "",
        views: 0,
        author: 1,
        istop: false,
        tags: [],
        plugins: [],
        status: 0,
      },
      i18,
      plugins,
      tagList: [],
      chosedTaglist: [],
      showTagInput: false,
      inputTag: "",
      cateList: [],
      rules: {
        title: { required: true, message: "标题为必填项", trigger: "blur" },
        ctime: { required: true, message: "时间必填哦！", trigger: "blur" },
        theme: { required: true, message: "主题要填啊。", trigger: "blur" },
        sortid: { required: true, message: "还没选分类呢", trigger: "blur" },
      },
    };
  },
  methods: {
    // 新增标签
    showInput() {
      this.showTagInput = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // 标签保存事件
    handleInputConfirm() {
      let inputTag = this.inputTag;
      if (inputTag) {
        this.addNewTag();
      }
      this.showTagInput = false;
      this.inputTag = "";
    },

    async addNewTag() {
      const res = await this.$http.post(`${this.adminPre}/tags`, {
        tagname: this.inputTag,
      });
      console.log(res);
      if (res.code == 200) {
        delete res.data.blogids;
        this.tagList.push(res.data);
        this.$message.success("添加标签成功！");
      } else {
        this.$message.error("标签添加失败");
      }
    },
    // 获取分类列表
    async getCateList() {
      const res = await this.$http.get("cate");
      this.cateList = res.data;
    },
    // 获取标签列表
    async GetTagsList() {
      const res = await this.$http.get("tags");
      this.tagList = res.data;
    },
    // ByteMd改变事件
    handleChange(val) {
      this.article.content = val;
      localStorage.setItem("m-blog", JSON.stringify(this.article.content));
    },
    // 获取标签类型名称
    getTagType(index) {
      return ["success", "warning", "info", "danger"][index % 4];
    },
    // 添加指定标签到文章的标签列表
    addTagToList(index) {
      this.chosedTaglist.push(this.tagList[index]);
      this.tagList.splice(index, 1);
    },
    // 移除指定标签
    tagRemove(index) {
      if (!this.tagList.includes(this.chosedTaglist[index])) {
        this.tagList.push(this.chosedTaglist[index]);
      }
      this.chosedTaglist.splice(index, 1);
    },
    //缓存至localstorage
    saveCache() {
      localStorage.setItem("m-blog", JSON.stringify(this.article.content));
      this.$message.success("缓存本地成功！");
    },
    // 点击了保存文章、 发布 按钮
    saveEditor() {
      let taglists = [];
      this.article.status = 1;
      this.chosedTaglist.forEach((item) => {
        taglists.push(item.id);
      });
      this.article.tags = taglists.join(",");
      this.sendSaveHttp();
    },
    // 发送请求HTTP
    async sendSaveHttp() {
      const res = await this.$http.post(`${this.adminPre}/blog`, this.article);
      if (res.code == 200) {
        this.$message.success("保存成功！");
        this.article.id = res.data;
      } else {
        this.$message.error("保存失败！请勿离开");
      }
    },
    // 来自编辑文章.先获取文章数据
    async getArtInfo() {
      const res = await this.$http.get(
        `${this.adminPre}/blog/${this.article.id}`
      );
      this.article = res.data;
      this.vditorValue = res.data.content;
      this.$nextTick(() => {
        this.initEditTags();
      });
    },
    //初始化已经添加了的标签
    initEditTags() {
      const aTagList = this.article.tags.split(",");
      let taglist = [];
      // 拆分成两块。一边是已经选择了的，一边是待选区
      for (let index = 0; index < this.tagList.length; index++) {
        const tag = this.tagList[index];
        if (aTagList.includes(tag.id + "")) {
          this.chosedTaglist.push(tag);
        } else {
          taglist.push(tag);
        }
      }
      this.tagList = taglist;
    },
    // 初始化。判断是否是编辑
    init() {
      if (this.$route.query.artid != undefined) {
        this.article.id = this.$route.query.artid;
        this.getArtInfo();
      } else {
        this.queryLocalStorage();
      }
      this.getCateList();
      this.GetTagsList();
    },
    //查询本地是否存在缓存？
    queryLocalStorage() {
      localStorage.getItem("m-blog")
        ? (this.article.content = JSON.parse(localStorage.getItem("m-blog")))
        : "";
    },
  },
  mounted() {
    this.init();
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  cursor: default;
  user-select: none;
  margin-top: 10px;
  margin-left: 10px;
}
.button-new-tag {
  margin-top: 10px;
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-top: 10px;
  margin-left: 10px;
  vertical-align: bottom;
}
.editor {
  .tags {
    margin-top: 10px;
  }
}
</style>
<style>
.bytemd {
  height: 700px;
}
</style>
